package com.loren.demo03.tcp2;

import com.loren.demo03.tcp0.TcpServerHandler;
import com.loren.demo03.tcp2.codec.CustomDecoder;
import com.loren.demo03.tcp2.codec.CustomEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TcpServer {

    private final int port;

    public TcpServer(int port) {
        this.port = port;
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024) // 队列长度之和
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new CustomEncoder());  // 编码器，发送消息时候用
                            channelPipeline.addLast(new CustomDecoder());  // 解码器，接收消息时候用 - 解决粘包拆包问题
                            channelPipeline.addLast(new TcpServerHandler()); // 业务处理器
                        }
                    });

            // 启动服务器并绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("TCP Server listening port is " + this.port);
                } else {
                    System.err.println("TCP Server listening port failed");
                }
            });
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new TcpServer(9001);
    }
}
